/**
 * 
 */
package com.anyuan.wx.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.anyuan.wx.message.resp.Article;
import com.anyuan.wx.message.resp.NewsMessage;
import com.anyuan.wx.message.resp.TextMessage;
import com.anyuan.wx.pojo.BaiduPlace;
import com.anyuan.wx.pojo.UserLocation;
import com.anyuan.wx.util.BaiduMapUtil;
import com.anyuan.wx.util.MessageUtil;
import com.anyuan.wx.util.MySQLUtil;

/**
 * @author liuyanbin
 * @date 2014-2-6
 */
public class CoreService{
	
	
	public static String processRequest(HttpServletRequest request){
	String respXml = null;
	String respContent = null;
	try 
	{
		Map<String,String> requestMap = MessageUtil.parseXml(request);
		//发送方账号
		String fromUsername = requestMap.get("FromUserName");
		//开发者账号
		String toUsername = requestMap.get("ToUserName");
		String msgType = requestMap.get("MsgType");
		
		TextMessage textMessage = new TextMessage();
		textMessage.setToUserName(fromUsername);
		textMessage.setFromUserName(toUsername);
		textMessage.setCreateTime(new Date().getTime());
		textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
		
		//文本消息
		if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT))
		{
			String content = requestMap.get("Content").trim();
			if(content.equals("附近"))
			{
				respContent = getUsage();
			}
			else if(content.startsWith("附近"))
			{
				String keyWord = content.replaceAll("附近", "").trim();
				//获取最后一次发送的地理位置
				UserLocation location = MySQLUtil.getLastLocation(request, fromUsername);
				//未获取到
				if(null == location)
				{
					respContent = getUsage();
				}else
				{
					//根据转化后的坐标搜索周边POI
					List<BaiduPlace> placeList = BaiduMapUtil.searchPlace(keyWord, location.getBd09Lng(), location.getBd09Lat());
					//未搜索到POI
					if(null ==placeList || 0 == placeList.size())
					{
						respContent = String.format("/难过，您发送的位置附近未搜索到"+content+"信息", keyWord);
					}else
					{
						List<Article> articleList = BaiduMapUtil.makeArticleList(placeList, location.getBd09Lng(), location.getBd09Lat());
						//创建图文消息
						NewsMessage newsMessage = new NewsMessage();
						newsMessage.setToUserName(fromUsername);
						newsMessage.setFromUserName(toUsername);
						newsMessage.setCreateTime(new Date().getTime());
						newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
						newsMessage.setArticles(articleList);
						newsMessage.setArticleCount(articleList.size());
						respXml = MessageUtil.messageToXml(newsMessage);
					}
				}
			} else
				respContent = getUsage();
			
		}	
		//
			else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION))
			{
				String lng = requestMap.get("Location_Y");
				String lat = requestMap.get("Location_X");
				
				String bd09Lng = null;
				String bd09Lat = null;
				
				UserLocation userLocation = BaiduMapUtil.convertCoord(lng, lat);
				if(null != userLocation)
				{
					bd09Lng = userLocation.getBd09Lng();
					bd09Lat = userLocation.getBd09Lat();
				}
				MySQLUtil.saveUserLocation(request, fromUsername,lng, lat, bd09Lng, bd09Lat);
				
				StringBuffer buffer = new StringBuffer();
				buffer.append("[愉快]").append("成功接收您的位置！").append("\n\n");
				buffer.append("您可以输入搜索关键词获取周边信息了，例如：").append("\n");
				buffer.append("              附件ATM").append("\n");
				buffer.append("              附件厕所").append("\n");
				buffer.append("              附件KTV").append("\n");
				buffer.append("必须以附近两个字开头！");
				respContent = buffer.toString();
			}
			else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT))
			{
				String eventType = requestMap.get("Event");
				if(eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE))
				{
					respContent = getSubscribeMsg();
				}
			}
			else
				{
					respContent = getUsage();
				}
				if(null != respContent)
				{
					textMessage.setContent(respContent);
					respXml = MessageUtil.messageToXml(textMessage);
				}
		
	} catch(Exception e)
	{
		e.printStackTrace();
	}
	
	return respXml;
	}
	
	private static String getSubscribeMsg()
	{
		StringBuffer buffer = new StringBuffer();
		buffer.append("您是否有过出门在外四处找ATM或厕所的经历");
		buffer.append("您是否有过出差在外搜寻美食或娱乐场所的经历");
		buffer.append("周边搜索为您的出行保驾护航，为您提供专业的周边生活指南，回复附近开始体验吧！");
		return buffer.toString();		
		
	}
	
	private static String getUsage()
	{
		StringBuffer buffer = new StringBuffer();
		buffer.append("周边搜索使用说明").append("\n\n");
		buffer.append("1)发送地理位置").append("\n");
		buffer.append("点击窗口底部的"+"按钮，选择"+"位置"+",点"+"发送"+"").append("\n\n");
		buffer.append("2)指定关键词搜索").append("\n");
		buffer.append("格式：附近+关键词\n例如：附近ATM、附近KTV、附近厕所");
		return buffer.toString();
	}

}
